package com.wzh.navcode.service.impl;

import com.wzh.navcode.adapter.TextBuilder;
import com.wzh.navcode.service.WxMsgService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;

/**
 * @Author: wangzh
 * @Version: 1.0
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class WxMsgServiceImpl implements WxMsgService {

    private final StringRedisTemplate stringRedisTemplate;

    @Value("${wx.open}")
    private String openUrl;

    @Value("${wx.mp.callback}")
    private String callbackUrl;

    @Override
    public WxMpXmlOutMessage scan(WxMpService weixinService, WxMpXmlMessage wxMessage) {
        String authorizeUrl = String.format(openUrl,
                weixinService.getWxMpConfigStorage().getAppId(),
                URLEncoder.encode(callbackUrl + "/api/wx/portal/public/callBack"));
        String content = String.format("你好请" + "<a href=\"%s\">点击授权</a>" + "进行登录", authorizeUrl);
        return TextBuilder.build(content, wxMessage, weixinService);
    }

    @Override
    public void save(WxOAuth2UserInfo userInfo) {
        stringRedisTemplate.opsForValue().set("user:info:", userInfo.getOpenid());
    }
}
